package com.spremoteservice.android;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.widget.Toast;

public class RemoteService {
	private String _siteUrl;
	private String _userName;
	private String _password;
	
	public RemoteService(String siteUrl, String userName, String password){
		this._siteUrl = siteUrl;
		this._userName = userName;
		this._password = password;
	}
	public Boolean ConnectTo(String appId) throws UnsupportedEncodingException{
        /*SoapObject request = new SoapObject("http://tempuri.org/", "ConnectTo");       
        
        //Use this to add parameters
        request.addProperty("appId",appId);
       
        //Declare the version of the SOAP request
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
       
        envelope.setOutputSoapObject(request);
        envelope.dotNet = true;
        
        String resultStr2 = "";
       
        try {
              HttpTransportSE androidHttpTransport = new HttpTransportSE(_siteUrl + ":9080/SPRemoteService");
             
              //this is the actual part that will call the webservice
              androidHttpTransport.call("http://tempuri.org/IRemoteService/ConnectTo", envelope);
             
              // Get the SoapResult from the envelope body.
              SoapObject result = (SoapObject)envelope.bodyIn;
              if(result != null)
              {
                    //Get the first property and change the label text
                    resultStr2 = result.getProperty(0).toString();
                    if(resultStr2.equalsIgnoreCase("true")){
                    	return true;
                    }else{
                    	return false;
                    }
              }
              else
              {
                    //Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
            	  return false;
              }
        } catch (Exception e) {
              e.printStackTrace();
        }
        return false;*/
        /*----------------*/
		
		Boolean result = false;
		HttpClient httpclient = new DefaultHttpClient();        
        ((AbstractHttpClient) httpclient).getAuthSchemes().register("ntlm",new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials(_userName, _password, "", "");

        ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000); 
        
        HttpPost httppost = new HttpPost(_siteUrl + "/_vti_bin/RemoteService/RemoteService.svc");
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        httppost.setHeader("SOAPAction", "http://tempuri.org/IRemoteService/ConnectTo");
	        
    	StringEntity se = new StringEntity("" +
    			"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
    			"	<s:Body>" +
    			"		<ConnectTo xmlns=\"http://tempuri.org/\">" +
    			"			<appId>" + appId + "</appId>" +
    			"		</ConnectTo>" +
    			"	</s:Body>" +
    			"</s:Envelope>", HTTP.UTF_8);
        se.setContentType("text/xml");
        httppost.setEntity(se); 

        HttpResponse httpresponse = null;
		try {
			httpresponse = httpclient.execute(httppost);
	        HttpEntity resEntity = httpresponse.getEntity();

		    String ConnectToResult = EntityUtils.toString(resEntity);
		   
	        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		        
	    	DocumentBuilder db = dbf.newDocumentBuilder();
	        Document doc = db.parse(new InputSource(new StringReader(ConnectToResult)));
	        NodeList resultNodeList = doc.getElementsByTagName("ConnectToResult");
	        Node resultNode = resultNodeList.item(0);
	        String resultStr = resultNode.getTextContent();
	        
	        if(resultStr.equalsIgnoreCase("true")){
	        	result = true;
	        }
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
        return result;

	}

	public Boolean OpenFile(String appId, String siteUrl, String filePath) throws UnsupportedEncodingException{
		Boolean result = false;
		HttpClient httpclient = new DefaultHttpClient();        
        ((AbstractHttpClient) httpclient).getAuthSchemes().register("ntlm",new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials(_userName, _password, "", "");

        ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000); 
        
        HttpPost httppost = new HttpPost(_siteUrl + "/_vti_bin/RemoteService/RemoteService.svc");
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        httppost.setHeader("SOAPAction", "http://tempuri.org/IRemoteService/OpenFile");
	        
    	StringEntity se = new StringEntity("" +
    			"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
    			"	<s:Body>" +
    			"		<OpenFile xmlns=\"http://tempuri.org/\">" +
    			"			<appId>"+ appId + "</appId>" +
    			"			<siteUrl>" + siteUrl + "</siteUrl>" +
    			"			<fileUrl>" + filePath + "</fileUrl>" +
    			"		</OpenFile>" +
    			"	</s:Body>" +
    			"</s:Envelope>", HTTP.UTF_8);
        se.setContentType("text/xml");
        httppost.setEntity(se); 

        HttpResponse httpresponse = null;
		try {
			httpresponse = httpclient.execute(httppost);
	        HttpEntity resEntity = httpresponse.getEntity();

		    String OpenFileResult = EntityUtils.toString(resEntity);
		   
	        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		        
	    	DocumentBuilder db = dbf.newDocumentBuilder();
	        Document doc = db.parse(new InputSource(new StringReader(OpenFileResult)));
	        NodeList resultNodeList = doc.getElementsByTagName("OpenFileResult");
	        Node resultNode = resultNodeList.item(0);
	        String resultStr = resultNode.getTextContent();
	        
	        if(resultStr.equalsIgnoreCase("true")){
	        	result = true;
	        }
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
        return result;
		
	}

	public Boolean PageDown(String appId) throws UnsupportedEncodingException{
		Boolean result = false;
		HttpClient httpclient = new DefaultHttpClient();        
        ((AbstractHttpClient) httpclient).getAuthSchemes().register("ntlm",new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials(_userName, _password, "", "");

        ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000); 
        
        HttpPost httppost = new HttpPost(_siteUrl + "/_vti_bin/RemoteService/RemoteService.svc");
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        httppost.setHeader("SOAPAction", "http://tempuri.org/IRemoteService/PageDown");
	        
    	StringEntity se = new StringEntity("" +
    			"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
    			"	<s:Body>" +
    			"		<PageDown xmlns=\"http://tempuri.org/\">" +
    			"			<appId>" + appId + "</appId>" +
    			"		</PageDown>" +
    			"	</s:Body>" +
    			"</s:Envelope>", HTTP.UTF_8);
        se.setContentType("text/xml");
        httppost.setEntity(se); 

        HttpResponse httpresponse = null;
		try {
			httpresponse = httpclient.execute(httppost);
	        HttpEntity resEntity = httpresponse.getEntity();

		    String PageDownResult = EntityUtils.toString(resEntity);
		   
	        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		        
	    	DocumentBuilder db = dbf.newDocumentBuilder();
	        Document doc = db.parse(new InputSource(new StringReader(PageDownResult)));
	        NodeList resultNodeList = doc.getElementsByTagName("PageDownResult");
	        Node resultNode = resultNodeList.item(0);
	        String resultStr = resultNode.getTextContent();
	        
	        if(resultStr.equalsIgnoreCase("true")){
	        	result = true;
	        }
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
        return result;
		
	}
	public Boolean PageUp(String appId) throws UnsupportedEncodingException{
		Boolean result = false;
		HttpClient httpclient = new DefaultHttpClient();        
        ((AbstractHttpClient) httpclient).getAuthSchemes().register("ntlm",new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials(_userName, _password, "", "");

        ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000); 
        
        HttpPost httppost = new HttpPost(_siteUrl + "/_vti_bin/RemoteService/RemoteService.svc");
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        httppost.setHeader("SOAPAction", "http://tempuri.org/IRemoteService/PageUp");
	        
    	StringEntity se = new StringEntity("" +
    			"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
    			"	<s:Body>" +
    			"		<PageUp xmlns=\"http://tempuri.org/\">" +
    			"			<appId>" + appId + "</appId>" +
    			"		</PageUp>" +
    			"	</s:Body>" +
    			"</s:Envelope>", HTTP.UTF_8);
        se.setContentType("text/xml");
        httppost.setEntity(se); 

        HttpResponse httpresponse = null;
		try {
			httpresponse = httpclient.execute(httppost);
	        HttpEntity resEntity = httpresponse.getEntity();

		    String PageUpResult = EntityUtils.toString(resEntity);
		   
	        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		        
	    	DocumentBuilder db = dbf.newDocumentBuilder();
	        Document doc = db.parse(new InputSource(new StringReader(PageUpResult)));
	        NodeList resultNodeList = doc.getElementsByTagName("PageUpResult");
	        Node resultNode = resultNodeList.item(0);
	        String resultStr = resultNode.getTextContent();
	        
	        if(resultStr.equalsIgnoreCase("true")){
	        	result = true;
	        }
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
        return result;
		
	}
	public Boolean CloseFile(String appId) throws UnsupportedEncodingException{
		Boolean result = false;
		HttpClient httpclient = new DefaultHttpClient();        
        ((AbstractHttpClient) httpclient).getAuthSchemes().register("ntlm",new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials(_userName, _password, "", "");

        ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000); 
        
        HttpPost httppost = new HttpPost(_siteUrl + "/_vti_bin/RemoteService/RemoteService.svc");
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        httppost.setHeader("SOAPAction", "http://tempuri.org/IRemoteService/CloseFile");
	        
    	StringEntity se = new StringEntity("" +
    			"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
    			"	<s:Body>" +
    			"		<CloseFile xmlns=\"http://tempuri.org/\">" +
    			"			<appId>" + appId + "</appId>" +
    			"		</CloseFile>" +
    			"	</s:Body>" +
    			"</s:Envelope>", HTTP.UTF_8);
        se.setContentType("text/xml");
        httppost.setEntity(se); 

        HttpResponse httpresponse = null;
		try {
			httpresponse = httpclient.execute(httppost);
	        /*HttpEntity resEntity = httpresponse.getEntity();

		    String PageUpResult = EntityUtils.toString(resEntity);
		   
	        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		        
	    	DocumentBuilder db = dbf.newDocumentBuilder();
	        Document doc = db.parse(new InputSource(new StringReader(PageUpResult)));
	        NodeList resultNodeList = doc.getElementsByTagName("PageUpResult");
	        Node resultNode = resultNodeList.item(0);
	        String resultStr = resultNode.getTextContent();
	        
	        if(resultStr.equalsIgnoreCase("true")){
	        	result = true;
	        }*/
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
        return true;
		
	}
}
